package com.kunyi.web.im.websocket.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import lombok.extern.slf4j.Slf4j;


/**
 * @ClassName WsSwitchHandler  WebSocket文本帧处理
 * @Description 自自定义的handel处理业务  参考：https://github.com/netty/netty/issues/7239
 * @Author zhenguo.zhuang
 * @Date 2024/03/29
 * @Version 1.0
 **/
@Slf4j
public class WsSwitchHandler  extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {
        if (msg instanceof FullHttpRequest) {
            String uri = ((FullHttpRequest) msg).getUri();
            String url = uri.substring(0, uri.indexOf("?"));
            String userId = uri.substring(uri.indexOf("name=") + 5, uri.indexOf("token=") - 1);
            ctx.pipeline().remove(this);
            // 判断url
            if ("/webSocket/message".equalsIgnoreCase(url)) {
                //2.请求时,地址为 ws://localhost:7000/xxx 表示请求连接的uri   注意xxx写啥浏览器请求地址的xxx就是啥
                //3.需要将http协议升级为ws协议,保持长连接
                ctx.pipeline().addAfter("HttpObjectAggregator", WebSocketServerProtocolHandler.class.getName(),
                        //checkStartsWith 表示通过url传参
                        new WebSocketServerProtocolHandler(uri,null,true,65536*10,false,true));
                //websocket它的数据是以帧（frame）的形式传递的
                ctx.pipeline().addAfter(WebSocketServerProtocolHandler.class.getName(), TextWebSocketFrameHandler.class.getName(), new TextWebSocketFrameHandler(userId));
            } else {
                ctx.channel().close();
                return;
            }

            // 重新开始执行一次pipeline
            ctx.pipeline().fireChannelRead(msg);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
    }

}
